//
//  TTDianpuUploadImageViewController.m
//  TaoTuo
//
//  Created by admin on 2019/11/7.
//  Copyright © 2019 admin. All rights reserved.
//

#import "TTDianpuUploadImageViewController.h"
#import "TTDianpuUploadImageModel.h"
#import "TTDianpuUploadImageCollectionViewCell.h"
#import "LLImagePicker.h"
#import "YBImageBrowser.h"
#import "OSSImageUploader.h"

static NSString *cellID = @"upload_cell_id";

static NSString *addImageName = @"addimage";

@interface TTDianpuUploadImageViewController ()<UICollectionViewDelegate, UICollectionViewDataSource, TTDianpuUploadImageCollectionViewCellDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate>

@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) NSMutableArray *imgUrlArray;  //上传的图片地址
///图片最大上传数量
@property (nonatomic, assign) int imageUploadMaxCount;
///是否是上传支付凭证图片
@property (nonatomic, assign) BOOL isUploadPayImage;
///订单号
@property (nonatomic, copy) NSString *orderNo;

///能否修改图片（上传支付凭证图片）
@property (nonatomic, assign) BOOL canModify;

@end

@implementation TTDianpuUploadImageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = self.isUploadPayImage ? @"上传支付凭证" : @"上传图片";
    self.imageUploadMaxCount = self.isUploadPayImage ? 6 : 8;
    if (!self.isUploadPayImage) {
        self.canModify = YES;
    }
    [self setupDatas];
    [self setupBottomView];
}

//- (void)backAction
//{
//    LLSystemAlertView *alertView = [LLSystemAlertView alertViewWithTitle:@"提示" message:@"如不保存，填写的信息将会丢失" cancelTitle:@"取消" cancelBlock:^{
//        [self.navigationController popViewControllerAnimated:YES];
//    } confirmTitle:@"保存" confirmBlock:^BOOL{
//        [self saveAction];
//        return YES;
//    }];
//    [TYShowAlertView showAlertViewWithView:alertView backgoundTapDismissEnable:YES];
//}

- (void)setIsUploadPayImage:(BOOL)isUploadPayImage orderNo:(NSString *)orderNo canModify:(BOOL)canModify
{
    self.isUploadPayImage = isUploadPayImage;
    self.orderNo = orderNo;
    self.canModify = canModify;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    TTDianpuUploadImageCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
    [cell setModel:self.dataArray[indexPath.row] canModify:self.canModify];
    cell.delegate = self;
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    TTDianpuUploadImageModel *lastModel = self.dataArray[indexPath.row];
    if ([lastModel.imageName isEqualToString:addImageName]) {
        // 点击了最后一个添加图片
        if (self.imgUrlArray.count >= self.imageUploadMaxCount) {
            NSString *hintStr = [NSString stringWithFormat:@"您最多只能选取%d张图片", self.imageUploadMaxCount];
            [self.view makeToast:hintStr];
            return;
        }
        [LLImagePicker imagePickerWithMaxImagesCount:self.imageUploadMaxCount delegate:self baseViewController:self didFinishPickingPhotosHandle:^(NSArray<UIImage *> * _Nonnull photos, BOOL isSelectOriginalPhoto) {
            //上传图片到OSS, 添加model
            [[OSSImageUploader sharedLoader] asyncUploadImages:photos complete:^(NSArray<NSString *> * _Nonnull names, UploadImageState state) {
                NSLog(@">>>> %@, state = %ld", names, state);
                for (NSString *urlStr in names) {
                    TTDianpuUploadImageModel *imgModel = [[TTDianpuUploadImageModel alloc] init];
                    imgModel.imageUrlString = urlStr;
                    [self.dataArray insertObject:imgModel atIndex:self.dataArray.count - 1];
                    [self.imgUrlArray insertObject:urlStr atIndex:self.imgUrlArray.count];
                }

                [self.collectionView reloadData];
            }];
        } canEdit:self.canEdit];
        
    } else {
        // 查看图片
        @autoreleasepool {
            NSMutableArray *imgs = [NSMutableArray array];
            for (TTDianpuUploadImageModel *model in self.dataArray) {
                if (model.imageUrlString.length > 0) {
                    YBIBImageData *imageData = [YBIBImageData new];
                    imageData.imageURL = [NSURL URLWithString:model.imageUrlString];
                    [imgs addObject:imageData];
                }
            }
            YBImageBrowser *browser = [YBImageBrowser new];
            browser.dataSourceArray = imgs;
            browser.currentPage = indexPath.row;
            [browser show];
        }
        
    }
}

// 拍照或选取图片完成
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<UIImagePickerControllerInfoKey,id> *)info
{
    // 图片
    UIImage *image = info[UIImagePickerControllerEditedImage];
    if (image == nil) {
        image = info[UIImagePickerControllerOriginalImage];
        NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
        image = [UIImage imageWithData:imageData];
    }
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    //上传图片到OSS, 添加model
    [[OSSImageUploader sharedLoader] asyncUploadImage:image complete:^(NSArray<NSString *> * _Nonnull names, UploadImageState state) {
        NSLog(@">>>> %@, state = %ld", names, state);
        NSString *urlStr = names.firstObject;
        TTDianpuUploadImageModel *imgModel = [[TTDianpuUploadImageModel alloc] init];
        imgModel.imageUrlString = urlStr;
        [self.dataArray insertObject:imgModel atIndex:0];
        [self.imgUrlArray insertObject:urlStr atIndex:0];
        [self.collectionView insertItemsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]]];
    }];
    
}

// 保存
- (void)saveAction
{
    self.isUploadPayImage ? [self savePaymentVouchersImages] : [self saveDianpuSetImages];
}

///店铺设置图片上传
- (void)saveDianpuSetImages
{
    NSArray *array = self.imgUrlArray.count > 0 ? self.imgUrlArray : @[];
    NSDictionary *dic = @{@"ShopImageList" : array};
    @weakify(self)
    [[LLNetworkManagerTool sharedManager] postJsonWithUrlString:uploadShopImg_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self)
        [[NSNotificationCenter defaultCenter] postNotificationName:@"refreashDatas" object:nil];
        [self.view makeToast:@"保存成功"];
        [self.navigationController popViewControllerAnimated:YES];
        if (self.uploadFinishedBlock) {
            self.uploadFinishedBlock(self.imgUrlArray);
        }
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
    } showLoadingInView:self.view];
}

- (void)savePaymentVouchersImages
{
    NSArray *array = self.imgUrlArray.count > 0 ? self.imgUrlArray : @[];
    NSDictionary *dic = @{
        @"RelationName" : [TTLoginSingle sharedSingle].loginModel.RealName,
        @"OrderNo" : self.orderNo,
        @"PaymentVouchers" : array
    };
    @weakify(self)
    [[LLNetworkManagerTool sharedManager] postJsonWithUrlString:uploadPaymentVouchers_api parameters:dic success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        @strongify(self)
        [self.view makeToast:@"保存成功"];
        [self.navigationController popViewControllerAnimated:YES];
        if (self.uploadFinishedBlock) {
            self.uploadFinishedBlock(self.imgUrlArray);
        }
        
    } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nullable error) {
        
    } showLoadingInView:self.view];
}

#pragma mark - TTDianpuUploadImageCollectionViewCellDelegate
// 删除图片
- (void)imageCell:(TTDianpuUploadImageCollectionViewCell *)imageCell deleteModel:(TTDianpuUploadImageModel *)model
{
    NSIndexPath *indexPath = [self.collectionView indexPathForCell:imageCell];
    [self.dataArray removeObject:model];
    [self.collectionView deleteItemsAtIndexPaths:@[indexPath]];
    
    for (NSString *urlStr in self.imgUrlArray) {
        if ([urlStr isEqualToString:model.imageUrlString]) {
            [self.imgUrlArray removeObject:urlStr];
            break;
        }
    }
}

- (void)setupDatas
{
    [self.dataArray removeAllObjects];
    
    for (NSString *str in self.imagesArray) {
        TTDianpuUploadImageModel *model = [[TTDianpuUploadImageModel alloc] init];
        model.imageUrlString = str;
        [self.dataArray addObject:model];
        [self.imgUrlArray addObject:str];
    }
    
    // 添加最后一个添加图片的按钮
    if (self.canModify) {
        TTDianpuUploadImageModel *lastModel = [[TTDianpuUploadImageModel alloc] init];
        lastModel.imageName = addImageName;
        [self.dataArray addObject:lastModel];
    }
    
    [self.collectionView reloadData];
    
}

- (void)setupBottomView
{
    UIButton *saveBtn = [UIButton createButtonWithTitle:@"保存" titleColor:[UIColor whiteColor] titleFont:[UIFont systemFontOfSize:18] backgroundColor:kMainColor target:self action:@selector(saveAction)];
    [self.view addSubview:saveBtn];
    [saveBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.mas_bottomLayoutGuideTop);
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(45);
    }];
    
    if (!self.canModify) {
        [saveBtn setTitle:@"该凭证已经超过45天啦，不允许修改！" forState:UIControlStateNormal];
        saveBtn.backgroundColor = UIColorHex(999999);
        saveBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        saveBtn.enabled = NO;
    }
    
}

- (UICollectionView *)collectionView
{
    if (!_collectionView) {
        CGFloat w = floor((self.view.width - 20) / 3.0);
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.itemSize = CGSizeMake(w, w);
        layout.minimumLineSpacing = 5;
        layout.minimumInteritemSpacing = 0;
        layout.sectionInset = UIEdgeInsetsMake(0, 8, 0, 8);
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = [UIColor whiteColor];
        [_collectionView registerClass:[TTDianpuUploadImageCollectionViewCell class] forCellWithReuseIdentifier:cellID];
        [self.view addSubview:_collectionView];
        [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.mas_topLayoutGuideBottom);
            make.left.right.equalTo(self.view);
            make.bottom.equalTo(self.mas_bottomLayoutGuideTop).mas_offset(45);
        }];
    }
    return _collectionView;
}

- (NSMutableArray *)dataArray
{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (NSMutableArray *)imgUrlArray
{
    if (!_imgUrlArray) {
        _imgUrlArray = [NSMutableArray array];
    }
    return _imgUrlArray;
}

@end
